package com.heyidlebooks.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.heyidlebooks.mgr.DatabaseConnectionMgr;
import com.heyidlebooks.mgr.Lucenev23Mgr;
import com.heyidlebooks.model.Book;

public class IndexCreator {

	private static final Logger LOG = Logger.getLogger(IndexCreator.class);
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String indexDir = args[0];
		Lucenev23Mgr luceneMgr = new Lucenev23Mgr(indexDir);
		Connection conn = DatabaseConnectionMgr.getConnection();
		IndexCreator creator = new IndexCreator();
		try {
			List<Book> books = creator.getActiveBooks(conn);
			luceneMgr.reindex(books);
			System.out.println("Reindex " + books.size() + " entries");
		} catch (SQLException e) {
			LOG.error(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					LOG.error("Error when close connection: " + e);
				}
			}
		}

	}
	
	private List<Book> getActiveBooks(Connection conn) throws SQLException {
		List<Book> books = new ArrayList<Book>();
		String sql = "SELECT * FROM book WHERE status = ?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, "active");
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			books.add(bookInfoMapper(rs));
		}
		return books;
	}

	private Book bookInfoMapper(final ResultSet rs) throws SQLException {
		Book book = new Book();
		book.setId(rs.getInt("id"));
		book.setIsbn(rs.getString("ISBN"));
		book.setASIN(rs.getString("ASIN"));
		book.setAuthor(rs.getString("author"));
		book.setBinding(rs.getString("binding") == null ? "" : rs.getString("binding"));
		book.setPublicationDate(rs.getDate("publication_date"));
		book.setTitle(rs.getString("name"));
		book.setDescription(rs.getString("description") == null ? "" : rs.getString("description"));
		book.setSmallImage(rs.getString("small_image") == null ? "" : rs.getString("small_image"));
		book.setMediumImage(rs.getString("medium_image") == null ? "" : rs.getString("medium_image"));
		book.setLargeImage(rs.getString("large_image") == null ? "" : rs.getString("large_image"));
		return book;
	}

}
